Skip to content

Provider: reversible add-on hold — stay connected, leave routing, unload models (local IPC for add-ons) - #1620

Merged
Gajesh2007 merged 3 commits into
masterfrom
provider/addon-hold
Oct 27, 2026
Merged

Gajesh2007 merged 3 commits into
masterfrom
provider/addon-hold

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Warning

Merging this publishes provider releases automatically. A push to master that touches provider-swift/** runs .github/workflows/release-swift.yml, which builds, signs (Developer ID) and publishes a dev release and a staging release in parallel (prod still needs a signed vX.Y.Z tag). Owner review is required before merge; this PR is a draft and requests no reviewers.

Summary

While a Mac runs Darkbloom Sandbox VMs (the separately installed add-on io.darkbloom.sandbox, team SLDQ2GJ6TL), the provider can now be held: it stays registered on its coordinator connection, leaves routing, finishes accepted work, unloads every model, and returns on the same connection the moment the add-on releases it. Naming is add-on neutral (addon) in provider code and on the wire.

Behavior

Phase What happens
hold Drain owner addonHold closes admission (coordinator and local). ProviderState.busy is published and an event heartbeat goes out at once with status: "draining" plus busy fields. Coordinator load_model/prefetch_model get the existing draining failure; desired_models is deferred; auto-update, Autopilot, revisions and MTP upgrades are deferred.
draining Accepted inference finishes, bounded by addonHoldDrainTimeoutDefault = .seconds(120) (the background update's budget); anything left is then cancelled. Load transitions get 60 s to settle.
held Every model is unloaded (owner decision) through unloadModel; retained KV segments and the MLX buffer cache are released. loaded-models.json is kept, as on shutdown, so the next start's preload plan is unchanged.
release Admission reopens, the activation reserve and capacity are rebuilt from a fresh memory sample (re-probed headroom), an idle/serving heartbeat goes out immediately, and a deferred desired_models snapshot is replayed. Models load on demand.
Lease expiry Leases are 30–600 s and renewed by the add-on. On expiry the provider probes ~/.darkbloom/runtime/ownership.lock with a non-blocking shared flock; it auto-releases only if no add-on holds the lock exclusively. Running VMs keep the Mac held.
Restart / update Active holds persist in ~/.darkbloom/runtime/addon-hold.json (0600). A restarted or updated provider closes admission before the local endpoint or startup preload can load anything, while a lease is valid or the lock is held.

Hazards from the review, handled:

  • No provider_drain barrier for a hold. The hold never sends it. An update or App Attest stall restart whose drain the hold took over stops before its barrier (waitForSafeDisconnect(underAddonHold:)). The App Attest worker is never stopped by a hold and can recover from an update stop while held (ProviderDrain.refusingForServiceChange).
  • Planned reconnects keep the hold. ProviderDrain.begin refuses to let update/reconnect/modelSwitch replace addonHold (only lifecycle preempts it); a planned reconnect runs beneath the hold, the fresh register carries the busy fields, and finishPlannedReconnect re-announces draining. A reconnect still pending at release keeps admission closed until its registration (resumeAfterAddonHold).
  • Startup. run()'s pre-registration abort checks now use refusingForServiceChange, so a restored hold no longer looks like a stop.

Wire fields (optional, backward compatible)

register and heartbeat gain busy_reason (closed vocabulary: addon), busy_since_ms (Unix ms the oldest hold began) and busy_addon (signer identifier, or operator for the CLI). They are omitted when not held, sent on heartbeats only beside status: "draining", and mirrored on the raw-attestation register path. Unknown busy_reason values decode as absent. Coordinator support lands separately in darkbloom-platform; coordinators on master already exclude a provider on status: "draining", refresh that mark on every draining heartbeat (150 s TTL) and clear it on the release heartbeat, and they ignore unknown provider keys. Autopilot's closed busy_reason(s) vocabulary gains addon_hold (reported instead of draining for the hold's own drain).

IPC contract (hold.v1)

Socket ~/.darkbloom/runtime/addon.sock (dir 0700, socket 0600; DARKBLOOM_ADDON_SOCKET for tests only). Newline-delimited JSON, ≤ 8 KiB per message, one response line per request, several requests per connection (≤ 8 connections, 300 s idle close).

Request Response
{"v":1,"op":"hello"} {"v":1,"ok":true,"capabilities":["hold.v1"],"provider_version":"x.y.z"}
{"v":1,"op":"hold","addon":"io.darkbloom.sandbox","vm_bytes":N,"lease_seconds":30..600} {"v":1,"ok":true,"hold_id":"<uuid>","state":"draining"|"held","since_ms":N,"lease_expires_at_ms":N} — idempotent, one active hold per add-on
{"v":1,"op":"status","hold_id":"..."} {"v":1,"ok":true,"state":"draining"|"held"|"released"|"expired","since_ms":N,"lease_expires_at_ms":N}
{"v":1,"op":"renew","hold_id":"...","lease_seconds":30..600} {"v":1,"ok":true,"state":...,"lease_expires_at_ms":N}
{"v":1,"op":"release","hold_id":"..."} {"v":1,"ok":true,"state":"released"}
errors {"v":1,"ok":false,"error":"unauthorized"|"unsupported_version"|"invalid_request"|"not_found"|"unavailable"}

Full reference: docs/reference/addon-hold-ipc.md; mechanism and invariants: docs/architecture/addon-hold.md.

Add-on client: Layr-Labs/darkbloom-sandbox#23 implements the same contract. It takes ownership.lock exclusively before holding (workers inherit the descriptor, so the lock outlives a crashed agent until its VMs are gone), sends hold with a 60 s lease, polls status until held, renews every 20 s, and treats held as no inference in flight and models unloaded — exactly the provider's held transition here. It re-holds on not_found/released/expired. Its socket-path override keeps ownership.lock beside the socket; DARKBLOOM_ADDON_SOCKET here does the same (lock and hold record move to the socket's directory), so test setups agree. Interplay to note from that PR: its control plane waits 15 s for an allocation, while this provider's drain may take up to 120 s plus unload; a slow drain declines that one allocation and the next one finds the Mac held.

Security notes

  • Same-UID coordination, not a boundary against the user. The provider and add-on run as the same user and can read each other's files; the socket and lock coordinate them. New threat-model entries TB-012, A-018, T-059.
  • Code-signature peer check on every request. LOCAL_PEERTOKEN audit token → same effective UID → SecCodeCopyGuestWithAttributes(kSecGuestAttributeAudit) (token incl. pidversion, never a PID or path) → requirement anchor apple generic and identifier "io.darkbloom.sandbox" and certificate 1[field.1.2.840.113635.100.6.2.6] and certificate leaf[field.1.2.840.113635.100.6.1.13] and certificate leaf[subject.OU] = "SLDQ2GJ6TL" + team/identifier + hardened runtime. The addon field must equal the verified signer; peers only see their own holds. Unauthenticated peers get unauthorized and are disconnected.
  • Release builds accept only the production identity. #if DEBUG builds may add one explicit DARKBLOOM_ADDON_DEV_IDENTITY=TEAMID:identifier (e.g. P7373SVQX6:io.darkbloom-test.sandbox); release builds compile without it.
  • Owner-only files read with O_NOFOLLOW + uid/mode checks; a live socket is never taken over; framing, connection count and idle time are bounded. Local transition logs ({"operation":"addon_hold",...} on stderr) carry no hold IDs, request IDs, models or content.

Operator CLI

darkbloom addon [status], darkbloom addon hold [--lease-seconds 30..600] (holds as operator), darkbloom addon release [--force] (refuses while the machine lock is held unless forced). They use the same-UID lifecycle mailbox bound to the live process identity. darkbloom status prints Not serving: held by add-on ….

Before / After

Before — behavior

flowchart LR
  classDef actor fill:#dbeafe,stroke:#1d4ed8,color:#0f172a
  classDef bad fill:#fee2e2,stroke:#b91c1c,color:#0f172a
  classDef neutral fill:#f1f5f9,stroke:#475569,color:#0f172a
  A["Sandbox add-on wants the Mac"]:::actor --> B{"Free the memory?"}:::neutral
  B -- "darkbloom stop" --> C["Drain + provider_drain barrier"]:::neutral --> D["Disconnect: offline, no earnings"]:::bad
  D --> E["Return = restart: new registration, authorization, warm-up"]:::bad
  B -- "do nothing" --> F["VMs compete with resident models"]:::bad
Loading

After — behavior

flowchart LR
  classDef actor fill:#dbeafe,stroke:#1d4ed8,color:#0f172a
  classDef good fill:#dcfce7,stroke:#15803d,color:#0f172a
  classDef state fill:#fef9c3,stroke:#a16207,color:#0f172a
  A["Add-on: hold (signed peer)"]:::actor --> B["Admission closed; heartbeat draining + busy_*"]:::state
  B --> C["Accepted work finishes (120 s bound)"]:::state --> D["All models unloaded: held"]:::state
  D --> E["VMs run; add-on renews lease"]:::actor
  E --> F["release (or lease expiry with lock free)"]:::actor --> G["Same connection: idle heartbeat, routing resumes"]:::good
  B -.->|"planned reconnect"| H["register carries busy_*; still held"]:::state
Loading

Before — code flow

flowchart TB
  classDef code fill:#ede9fe,stroke:#6d28d9,color:#0f172a
  classDef risk fill:#fee2e2,stroke:#b91c1c,color:#0f172a
  O["ProviderDrain owners: update, reconnect, modelSwitch, lifecycle"]:::code
  P["startPlannedReconnectIfNeeded: begin(.reconnect)"]:::code --> Q["finishPlannedReconnect: resumeReconnect, reopen admission"]:::risk
  R["run(): servingDrain.refusing means stop before registration"]:::code
  S["heartbeat: status only"]:::code
Loading

After — code flow

flowchart TB
  classDef code fill:#ede9fe,stroke:#6d28d9,color:#0f172a
  classDef new fill:#dcfce7,stroke:#15803d,color:#0f172a
  I["AddonIPCServer: audit token -> AddonPeerPolicy"]:::new --> H["ProviderLoop.handleAddonIPC"]:::new
  CLI["darkbloom addon -> LifecycleMailbox"]:::new --> H
  H --> HF["holdForAddon -> enterAddonHold"]:::new
  HF --> D1["ProviderDrain.begin(.addonHold); ProviderState.busy; sendEventHeartbeat"]:::code
  HF --> ST["settleAddonHold: drain wait -> unloadModel x N -> releaseReclaimableMemoryForLoad"]:::new
  M["enforceAddonHoldLeases + AddonMachineLock.observe"]:::new --> RL["endAddonHold -> leaveAddonHold"]:::new
  H --> RL
  RL --> RS["resumeAfterAddonHold -> announceAddonHoldRelease: capacity, heartbeat, desired_models replay"]:::new
  PR["planned reconnect: owner .reconnect or .addonHold; register busy_*"]:::code
  RUN["run(): startAddonHoldService restores AddonHoldStore before preload; refusingForServiceChange"]:::code
Loading

Validation

macOS 27.0.1 (26A434), Xcode Swift 6.4, Apple Silicon; state isolated as in scripts/run-provider-tests.sh. Commit e32528c is signed and Verified on GitHub.

Command Result
make provider-test steps on base ad7dd816e: swift build --build-tests, scripts/stage-test-metallib.sh, scripts/run-provider-tests.sh with the documented fixtures (prepare-mimo-provider-fixtures.py, prepare-mimo-prompt-fixtures.py) All 18 Swift Testing runs passed: general runs 4,772 tests / 641 suites and 692 / 114, every isolated suite, the exclusive allocator test. XCTest: one failure, ProviderCoreFoundationTests.PageCacheTests.testHashingDropsPagesThatWereCachedBeforeTheRead (OS page residency after hashing: 33554432 ≠ 0). That target depends only on ProviderBuildEnvironment and ProviderCoreFoundation, untouched here; it passed 3/3 in isolation before and after the rebase (load-sensitive flake)
Python steps of make provider-test: test_protocol_fixture_resources.py, test-stage-test-metallib.py, test-stage-swiftpm-resource-bundles.py OK
Rebased onto 0af5e1c86 (0.10.3 hotfix: host-only jit_kernels.cpp; tree-keyed metallib digest unchanged), rebuilt, then every touched suite: the new suites plus ProviderLifecycleTests, ProviderModelSwitchTests, UpdateDrainAwarenessTests, AutoUpdateCycleTests, AppAttestUpdateLifecycleTests, StartupPreloadTests, StandaloneStartupPreloadTests, LifecycleMailboxTests, ModelSlotBookkeepingTests, RetirementGateTests, TransitionWatchdogTests, ServeLoop{Connection,Dispatch,AppAttest,ColdLoad}Tests, ProviderAuthorizationConnectionTests, Coordinator{Client,Integration,ModelSwitch}Tests, HeartbeatIdlePolicyTests, CapacityEventHeartbeatTests, ProtocolTests, AppAttestResumeTransportTests, NativeMediaToolsCapabilityTests, Autopilot{SnapshotCoding,Adoption,BusyReason}Tests, CLIDispatchTests, StatusCommand*, SwitchCommand*, WatchdogTests, DaemonState*, PageCacheTests 406 tests / 56 suites and 30 / 7 passed; PageCacheTests 3/3
make changelog-check, make changelog-preview, make docs-check, make docs-impact-check BASE=origin/master OK (4 fragments; 198 docs; 54 changed files covered)
Lint Swift has no repository-enforced formatter; git diff --check clean

New tests (51, all passing), in provider-swift/Tests/ProviderCoreTests/Addon/ and provider-swift/Tests/DarkbloomCLITests/AddonCommandTests.swift:

  • Drain-owner precedence: update/reconnect/switch cannot replace or reopen a hold; only a stop preempts it; a hold never preempts a switch or stop (AddonHoldDrainOwnershipTests, AddonHoldLoopTests.updateDrainAndReconnectCannotReopenAHold, aStopTakesOverAndNoNewHoldIsAcceptedWhileStopping).
  • Planned reconnect keeps the hold; register carries the fields: end to end against the loopback coordinator with the real socket: draining heartbeat with busy_*, no provider_drain frame, 503 draining rejection while held, requestPlannedReconnect → second register with busy_*, release → idle heartbeat without them (AddonHoldServeLoopTests).
  • Lease expiry with/without the lock (real flock), restart restore (valid lease, expired + lock held, expired + free), unload-all with the preload set kept and the App Attest worker untouched, bounded drain, resume + deferred desired_models replay, operator mailbox (AddonHoldLoopTests).
  • IPC parsing/limits/errors/idempotency and exact response keys (AddonIPCTests); real socket permissions, several requests per connection, oversized line, unauthenticated peer refused by the real Security-framework policy, stale vs live socket (AddonIPCServerTests); owner-only record and lock probe (AddonHoldStoreTests); production requirement string compiles and refuses the test process (AddonPeerPolicyTests).
  • Heartbeat and both register encoders, unknown-reason tolerance, no busy fields beside a routable status (ProviderBusyWireTests); CLI parsing/rendering and daemon-state round trip (AddonCommandTests).

Not run: interop with a real signed io.darkbloom.sandbox build (no signed add-on on this runner; the socket and serve-loop flows inject an authenticator, the peer policy is tested negatively); GPU/full-model qualification (unaffected by this change).

Limitations and follow-ups

  • Coordinator handling of busy_* (immediate exclusion on register, dashboards) is separate darkbloom-platform work; until then the draining status alone excludes the provider, and a request that races a fresh registration gets the typed draining 503.
  • The positive peer path (a real signed io.darkbloom.sandbox) is not exercised in CI; tests use the real policy negatively and an injected authenticator for the socket/serve flows. Physical interop with the add-on is a separate check.
  • Add-on entitlements are not inspected beyond the hardened runtime (spec); the add-on team should avoid get-task-allow and library-validation exemptions in release builds.
  • Dev/staging provider installs serve their own runtime directory (~/.darkbloom-dev/runtime/addon.sock, …), so the add-on's socket_path must point there to hold a dev install; production is exactly ~/.darkbloom/runtime/….
  • A hold is refused (unavailable) while a model switch owns admission; leases use wall-clock time (the lock fallback covers running VMs).
  • Refactor pass (AGENTS.md "Required Refactor Pass"): done by an independent refactor subagent; commit 3332b52 (signed, Verified), behavior-preserving. Changes: the CLI validates --lease-seconds against the provider's own bounds (AddonHoldControlRequest.leaseSecondsRange, from AddonHold.leaseSecondsRange) instead of a copied 30...600 (the provider drops an out-of-range request unanswered) and names its 10 s answer timeout once; help and error text are byte-identical. AddonHoldBook owns its machine-lock keep set (recordRenewal, keepForMachineLock). AddonIPCServer builds the socket address for bind and connect in one helper (withAddress) and names its write timeout. The AddonHoldControlRequest.isValid comment cited the drain request's window; it now documents the actual 60 s window (drain and switch requests allow 3605 s; behavior unchanged, so confirm 60 s is intended). Reviewed and left as is: drain-owner precedence, planned reconnect and resumeAfterAddonHold, the startup refusingForServiceChange checks, wire encoders, peer policy, IPC framing. Rerun after the change: swift build --build-tests (no new warnings), scripts/stage-test-metallib.sh, the add-on selector (51 tests: 47 in 9 suites + 4 in 1), every touched suite listed above with the documented MiMo provider fixtures (406 tests / 56 suites and 30 / 7 passed; XCTest 0 failures, PageCacheTests 3/3), make changelog-check, make docs-check, make docs-impact-check BASE=origin/master, git diff --check: all pass. Without MIMO_V26_SERIAL_LOAD_FIXTURES the two "genuine strict scanner quote" startup tests fail at fixture lookup, as documented.

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

While a local add-on (the Darkbloom Sandbox VM host) uses the Mac, the
provider stays registered on its coordinator connection, leaves routing
and returns on the same connection when released.

- Drain owner `addonHold`: update, reconnect and model-switch drains can
  neither replace nor reopen it; only a stop preempts it. The hold never
  sends `provider_drain` and never stops the App Attest worker. Planned
  reconnects run beneath the hold and the fresh `register` keeps it.
- Hold: close admission, announce `status: draining` with optional
  `busy_reason` / `busy_since_ms` / `busy_addon` (heartbeat and register,
  both register encoders), finish accepted work within 120 s, unload
  every model and free retained KV segments and the MLX buffer cache.
  Release reopens admission, re-probes capacity, sends an idle/serving
  heartbeat and replays deferred `desired_models`.
- Leases of 30-600 s; an expired lease ends the hold only when no add-on
  holds `ownership.lock`. Active holds persist owner-only so a restarted
  or updated provider comes back held before any model can load.
- `hold.v1` on `~/.darkbloom/runtime/addon.sock` (0700/0600): newline JSON,
  8 KiB limit, hello/hold/status/renew/release, per-request audit-token
  code-signature check (io.darkbloom.sandbox, team SLDQ2GJ6TL, hardened
  runtime, same UID; DEBUG builds may add one explicit identity).
- `darkbloom addon status|hold|release` through the lifecycle mailbox,
  Autopilot busy reason `addon_hold`, local structured transition logs,
  and the status line for a held provider.
- Docs (architecture, IPC reference, protocol, CLI, configuration,
  Autopilot, tests), threat model TB-012/A-018/T-059, changelog fragment.
@vercel

vercel Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
d-inference Ready Ready Preview Oct 27, 2026 1:14am UTC
d-inference-console-ui-dev Ready Ready Preview Oct 27, 2026 1:14am UTC
d-inference-landing Ready Ready Preview Oct 27, 2026 1:14am UTC
darkbloom-status Ready Ready Preview Oct 27, 2026 1:14am UTC
eigen-homepages-darkbloom Ready Ready Preview Oct 27, 2026 1:14am UTC

Request Review

…rnals

Behavior-preserving refactor pass over the add-on hold:

- The CLI validates --lease-seconds against the provider's own bounds
  (AddonHoldControlRequest.leaseSecondsRange) instead of a copied literal;
  the provider drops an out-of-range request unanswered. The CLI's answer
  timeout is named once. Help and error text are unchanged.
- AddonHoldBook owns its machine-lock keep set: a renewal clears it and
  the lease check asks the book whether a keep is new.
- AddonIPCServer builds the socket address for bind and connect in one
  helper and names its write timeout.
- AddonHoldControlRequest.isValid documents its actual 60 s window (the
  comment wrongly cited the drain request's).
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T01:41:32.222384Z e164315 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Threat model review — advisory

Reviewed head e164315dc41b against base 11bb2d18cef8.

Reviewers: anthropic/claude-sonnet-5.5: first pass completed; anthropic/claude-opus-5.5: selected depth completed (35 batches); openai/gpt-6.1-sol: selected depth completed (30 batches)

LOW: New add-on local IPC/mailbox control channel is not covered by the threat model

provider-swift/Sources/ProviderCore/Addon/AddonPeerPolicy.swift:57 · TB-003

This PR adds a local control surface that can close serving admission, cancel in-flight inference after 120s, and unload every model. Callers are code-signature-authenticated sockets (AddonPeerPolicy.authenticate) and the operator mailbox (handleAddonControl). No TB/T entry covers this boundary: socket location and permissions, per-connection versus per-request authentication, lease bounds, or the rule that an expired lease is kept while the machine lock is held (ProviderLoop+AddonHold.swift:322-334, 142-146). The lock appears to be observed through a plain file, so any same-UID process that takes it could keep the provider held indefinitely. The same-UID user is already the operator (ADV-001), so this is an availability and documentation gap rather than a confidentiality regression. Fix: add a TB entry and threat for the add-on hold, recording the peer policy, lease clamps, machine-lock semantics and fail-open on an unreadable hold record (ProviderLoop+AddonHold.swift:366-368).

Raised by: anthropic/claude-sonnet-5.5

LOW: New add-on hold IPC surface cites an undefined threat-model boundary (TB-012)

docs/reference/addon-hold-ipc.md:94 · TB-002, TB-003

docs/reference/addon-hold-ipc.md documents a new local AF_UNIX `hold.v1` control surface (~/.darkbloom/runtime/addon.sock). Over it, a code-signed add-on can make the provider drain or hold serving capacity, and an expired lease is kept while the add-on holds ownership.lock. The doc points readers to threat-model `TB-012` (line 96), but the base canonical model defines boundaries only through TB-011. No asset, threat or mitigation covers this boundary. Nothing in the model covers the same-user peer-token and code-requirement check, the DEBUG-only `DARKBLOOM_ADDON_DEV_IDENTITY` acceptance, the `DARKBLOOM_ADDON_SOCKET` path override, or the indefinite availability hold through ownership.lock. The new `darkbloom addon` lifecycle-mailbox commands in cli-reference.md are also unmodeled. Trigger: a reviewer relies on TB-012 to evaluate this surface, but no TB-012 exists. Impact: provider availability and drain controls stay unreviewed against TB-003 and TB-002. The model also does not record that busy fields reported to the coordinator are self-reported. Fix: add TB-012 and its threats to docs/threat-model.yaml. The new entries should record that the socket is not a boundary against the same user. They should state whether release builds honor DARKBLOOM_ADDON_SOCKET. They should also bound how long a hold can persist.

Raised by: anthropic/claude-opus-5.5

MEDIUM: Unauthenticated connections can exhaust all add-on IPC slots

provider-swift/Sources/ProviderCore/Addon/AddonIPCServer.swift:128 · new attack surface

Connections enter the eight-slot connection set before peer authentication, which occurs only after a complete request line arrives (lines 155–158 and 186–189). An unsigned same-UID program can open eight sockets and send nothing, denying service to the legitimate signed add-on for the 300-second idle timeout; reconnecting repeats the denial. The signature policy therefore does not protect availability of hold, status, release, or renewal operations. Authenticate the kernel peer token before admitting a connection, and bound incomplete-request time independently of received-byte activity.

Raised by: openai/gpt-6.1-sol

LOW: Hold-record validation can block indefinitely on a FIFO

provider-swift/Sources/ProviderCore/Addon/AddonHoldStore.swift:26 · TB-003

read() opens the hold-record path in blocking mode before checking that it is a regular file. A same-UID process can replace addon-hold.json with a FIFO containing no writer; open() then blocks indefinitely, so the subsequent fstat validation never returns .invalid. O_NOFOLLOW does not prevent this. This exposes the persisted-hold reader to a local availability attack whenever restoration reads the record. Open with O_NONBLOCK, then validate the descriptor as a regular file before reading.

Raised by: openai/gpt-6.1-sol

Models: budgeted Sonnet / selective Opus / selective Sol 6.1. Findings require human validation; this review never requests changes or blocks merging.

Scan completed; human review required.
Cross-file reviewer requests further review; independent human review required; Final reviewer requests further review; independent human review required

Coverage: 249/249 source units; cross-file integration complete. 0 selected depth batch(es) pending. All threat definitions indexed; relevant full definitions selected. Unchanged callers are not scanned.

Cost this run: $0.0000 reported, $0.0000 reserved with unknown cost; 0 paid request(s), 66 reused batch(es), 0 provider cache-hit tokens.

Saved findings and earlier report · Historical findings are not confirmed resolved.

Bedrock: 48 request(s), 867194 uncached + 0 cache-read + 948304 cache-write input / 35169 output tokens; 0 request(s) with unknown usage. OpenRouter backup used 0 time(s). Dollar amounts above cover OpenRouter only; AWS billing is reconciled separately.
Workload allowance: 115 native request(s), including one shared response repair; 500 emergency ceiling. Selected depth and integration rounds are admitted as their scope becomes known.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3332b520aa

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Gajesh2007
Gajesh2007 marked this pull request as ready for review October 27, 2026 01:37

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e164315dc4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Gajesh2007
Gajesh2007 merged commit bab16fe into master Oct 27, 2026
41 of 42 checks passed
jonathan308 added a commit that referenced this pull request Oct 27, 2026
Brings in #1615, #1618 (provider 0.10.3 hotfix), #1617, #1619 and #1620
(reversible add-on hold).

Conflicts and resolutions:
- docs/provider/cli-reference.md: only the "Last updated" stamp
  conflicted (2026-10-26 here, 2026-10-27 on master). Kept the one
  2026-10-27 stamp; both texts are kept (this branch's served-count lines
  and master's `darkbloom addon` section merged cleanly).

No semantic interplay with #1620: the served counts and the add-on hold's
"Not serving: held by add-on" status line are independent.
jonathan308 added a commit that referenced this pull request Oct 27, 2026
Brings in #1615, #1618 (provider 0.10.3 hotfix), #1617, #1619 and #1620
(reversible add-on hold).

Conflicts and resolutions:
- docs/provider/cli-reference.md: only the "Last updated" stamp
  conflicted (2026-10-26 here, 2026-10-27 on master). Kept the one
  2026-10-27 stamp; both texts are kept.
- docs/reference/protocol-messages.md: only the "Last updated" stamp
  conflicted. Kept the one 2026-10-27 stamp; this branch's no-session
  drain text and master's busy_reason/busy_since_ms/busy_addon fields
  merged cleanly.

provider-swift/Sources/ProviderCore/ProviderLoop+Lifecycle.swift merged
cleanly: #1620 changes beginServingDrain and the lifecycle monitor, this
branch only the end of performLifecycleDrain (coordinatorSettled).

Interplay with #1620, reviewed: an add-on hold keeps its registered
connection, so the stop path still waits for the coordinator's drain
acknowledgement while held; only a stop without a registered session
skips it. A planned reconnect under a hold goes through the bounded
handshake, and its fresh register still carries the busy fields.
jonathan308 added a commit that referenced this pull request Oct 27, 2026
Brings in #1615, #1618 (provider 0.10.3 hotfix), #1617, #1619 and #1620
(reversible add-on hold).

Conflicts and resolutions:
- provider-swift/Sources/ProviderCore/Service/DaemonState+Coding.swift:
  both sides appended a daemon-state key to the same CodingKeys line
  (`coordinatorConnection` here, `addonHold` from #1620). Kept both as
  `case autopilotState, coordinatorConnection, addonHold`, matching the
  struct's field order and the encode order. The decode/encode bodies
  merged cleanly; both keys stay optional (decodeIfPresent and
  encodeIfPresent), so files from older daemons still decode and older
  readers ignore the new keys.
- docs/provider/cli-reference.md: only the "Last updated" stamp
  conflicted (2026-10-26 here, 2026-10-27 on master). Kept the one
  2026-10-27 stamp; both texts are kept (this branch's Traffic line and
  master's `darkbloom addon` section).

DaemonStateFile.swift and ProviderLoop+Trust.swift merged cleanly: the
DaemonState initializer takes coordinatorConnection before appAttest and
addonHold last, and writeDaemonState passes both in that order.
jonathan308 added a commit that referenced this pull request Oct 27, 2026
… holds the Mac

With master's add-on hold (#1620) merged, a held provider stays connected
and authorized but leaves routing on purpose (status: draining). The
traffic verdict ignored the hold: `darkbloom status` printed
"Not serving: held by add-on ..." followed by "Traffic: eligible for
coordinator work (App Attest authorized until ...)", doctor passed
`coordinator traffic`, and once the lease lapsed or a reconnect under the
hold went unconfirmed both reported "NOT receiving coordinator work" with
an authorization cause and a `darkbloom restart` fix, which a hold
survives.

ServingReadiness.verdict now returns no verdict while an add-on holds a
connected Mac, so status omits the Traffic line (as it does beside a
drain line) and doctor skips the check. A disconnect is still reported.
Re-registration needed no change: superviseServingAuthorization already
waits while autopilotBusyReasons() is non-empty, which includes
addon_hold.

Tests (fail on the merge commit, pass here):
- ServingReadinessTests.aConnectionAnAddonHoldsHasNoVerdict
- StatusCommandRunTests.heldProviderHasNoTrafficVerdict

Docs: cli-reference (Traffic line), troubleshooting (coordinator traffic
row); changelog fragment coordinator-traffic-verdict.md updated in place.
jonathan308 added a commit that referenced this pull request Oct 27, 2026
Brings in #1615, #1618 (provider 0.10.3 hotfix), #1617, #1619 and #1620
(reversible add-on hold).

Conflicts and resolutions:
- docs/architecture/model-autopilot.md: only the "Last updated" stamp
  conflicted (2026-10-26 here, 2026-10-27 on master). Kept the one
  2026-10-27 stamp; both texts are kept (this branch's selected-model
  recovery sections and master's `addon_hold` busy reason).
- docs/provider/cli-reference.md: only the "Last updated" stamp
  conflicted. Kept the one 2026-10-27 stamp; both texts are kept.

Code merged cleanly, including ProviderLoop+AutopilotBusy.swift (the
recovery attempt counts as `preload`; #1620 adds `addon_hold`),
DaemonState+Coding.swift (selectedModelRecovery and addonHold keys) and
ProviderLoop+ModelLoading.swift (an unload makes waiting recoveries due;
an add-on hold's unload keeps the persisted serving set).

Interplay with #1620, reviewed: a recovery check pauses while the hold
owns admission (servingDrain.refusing), and the hold's unload pass waits
for a running attempt (modelSwitchMutationsSettled). The hold did not
cancel an attempt already loading; the next commit fixes that.
jonathan308 added a commit that referenced this pull request Oct 27, 2026
…load in progress

With master's add-on hold (#1620) merged, a selected-model recovery check
pauses while the hold owns admission, but an attempt that was already
loading kept going: enterAddonHold cancelled coordinator preloads only.
The hold's unload pass waits for loads at most addonHoldSettleTimeout
(60 s) and then marks the Mac held, so a longer recovery load (a large
model) could finish and install its slot after the add-on was told the
models were unloaded, beside its VMs. A shorter one was loaded only to be
unloaded again, and its entry left the recovery queue.

enterAddonHold now also cancels selectedModelRecovery.attempt, exactly as
it cancels preloadTasks. The load path honours cancellation before it
installs a slot, the attempt treats CancellationError as "keep waiting",
so the model stays queued and is retried after the release.

Test (fails on the merge commit after 13 s: "the recovery load kept
running under the hold"; passes here in 0.2 s):
- SelectedModelRecoveryPolicyTests.anAddonHoldCancelsTheAttemptInProgress

Docs: addon-hold.md invariant 5, model-autopilot.md recovery section;
changelog fragment selected-models-recover.md updated in place.
jonathan308 added a commit that referenced this pull request Oct 27, 2026
…regression

Brings in the M5 head-dim split attention hotfix (#1618: libs/mlx
31f550af, libs/mlx-swift 4926d3d9) and the add-on hold (#1620). Without
the hotfix, Gemma 4 26B prefill of 1,024 or more tokens exits on M5 GPUs,
so qualification builds of this branch must include it.

Conflicts were the "Last updated" lines in docs/provider/cli-reference.md
and docs/reference/configuration.md; master's 2026-10-27 is kept. The
branch's diff against master is unchanged: the Gemma QAT exact acceptance
default, its config comment, tests, docs and changelog fragment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Oct 27, 2026
…oundation

Master's reversible add-on hold adds a busy field to registration and heartbeat beside this branch's cluster fields. Every conflict keeps both: Register carries the member role, nonce, cluster models and membership and then busy; Heartbeat carries cluster_session and then busy; the codec, registration sender and client state pass both; the protocol reference lists both. Startup keeps the control-only member's skipped catalog prewarm and takes master's refusingForServiceChange, so an add-on hold at startup does not shut the provider down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Oct 27, 2026
…restoration fix

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Oct 27, 2026
…nto the cluster beta

Brings master's reversible add-on hold through #1407's resolution (cluster fields and busy side by side in registration and heartbeat). Only the freshness stamps of three reference pages conflicted here; they take the later date. Gitlinks unchanged: libs/mlx ea318ee0, libs/mlx-swift 31ffa0d, libs/mlx-swift-lm b6650465.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
davidtai added a commit that referenced this pull request Oct 27, 2026
The merge adds #1615, #1617, #1618 (provider 0.10.3 hotfix), #1619 and
#1620 (reversible add-on hold) to this branch.

Conflicts and resolutions:
- docs/provider/cli-reference.md: only the "Last updated" stamp had a
  conflict (2026-10-26 on this branch, 2026-10-27 on master). The merge
  keeps one stamp, 2026-10-27. It keeps the two texts: the reconnect
  rows of this branch in the runtime constants, and the `darkbloom addon`
  section and the add-on runtime row of master.
- docs/reference/protocol-messages.md: only the "Last updated" stamp had
  a conflict. The merge keeps one stamp, 2026-10-27. Git put the
  "Add-on hold busy fields" section of master and the "Close codes and
  the reconnect wait" section of this branch one after the other, after
  "Provider lifecycle drain". The file has each section one time.

Git merged all code without a conflict. Only CoordinatorClientState.swift
changed on the two sides. Master adds the ProviderState.busy property.
This branch adds the CoordinatorSessionRecorder class. These changes are
in different types. The new code of master does not call the symbols
that this branch changes: ExponentialBackoff.nextDelay(), the private
functions in CoordinatorClient+Connection.swift and
MockCoordinator.dropActiveWebSocket. The gitlinks are those of master:
libs/mlx 31f550af, libs/mlx-swift 4926d3d9, libs/mlx-swift-lm aee6ebb6.
Against master, the branch has the same changes as before, except the
two stamps.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Oct 27, 2026
Brings in #1615, #1617, #1618 (provider 0.10.3 hotfix), #1619, #1620 and
#1623 (add-on hold), #1621 (Qwen JSON response formats without default
thinking) and #1622 (Qwen JSON response_format answers under the JSON
grammar).

Conflicts and resolutions:
- docs/architecture/inference.md: only the "Last updated" stamp
  conflicted (2026-10-26 here, 2026-10-27 on master). Kept the one
  2026-10-27 stamp; both texts are kept (this branch's forced-admission
  table and whitespace rule, and master's constrained Qwen JSON answer
  sections, merged cleanly).

Interplay with #1621 and #1622 (same Qwen 3.5/3.6 families):
- QwenJSONAnswerPolicy installs the JSON grammar only for requests with
  no tools and no tool_choice, so a forced request keeps this branch's
  prompt-forced, withheld and post-validated path with no token
  constraint, also when it carries a JSON response_format.
- templateAdditionalContext turns thinking off for forced legacy Qwen
  before #1621's JSON default is consulted; both give
  enable_thinking=false, and caller controls stay overridden on the
  forced path as before.
- NativeToolStreamRouter drops framing whitespace only when a tool call
  is required. A constrained JSON answer is never forced, so its bytes,
  including whitespace, stream unchanged.
Gajesh2007 pushed a commit that referenced this pull request Oct 27, 2026
…er a connection left unauthorized (#1607)

* Say why a connected provider gets no coordinator work, and re-register when it is never authorized

A provider can stay connected, heartbeating and passing legacy challenges
while the coordinator refuses to route to it: no App Attest lease and no
legacy authorization. Public /v1/stats showed 74-79 of ~1,150 connections
(about 7%) in that state in every snapshot from 2026-10-25 17:06Z to
2026-10-26 05:18Z, many for more than 11 hours. `darkbloom status` showed
them as healthy, or as `Trust: awaiting coordinator status`, so operators
restarted blindly or asked whether they were banned.

- ServingReadiness turns the daemon state into a verdict: eligible, not yet
  (just connected), or not receiving coordinator work with the cause and a
  fix: disconnected (with the registration count, which exposes a reconnect
  loop), no coordinator verdict 90 s after connecting, an expired App
  Attest lease, or the coordinator's reason for not authorizing the
  connection, refined by the local App Attest observation (stalled Apple
  call, macOS below 27, App Attest unavailable outside the GUI session,
  locked keychain, no linked account).
- `darkbloom status` prints it as a `Traffic:` line with `→ fix:`, and
  `darkbloom doctor` as the `coordinator traffic` check.
- The daemon state file records the coordinator connection
  (`coordinator_connection`: connected, since, connections).
- The provider re-registers, through the existing planned-reconnect drain,
  a connection the coordinator has not authorized for 15 min plus a 0-15 min
  per-process jitter, then after 30 min, 1 h, 2 h and every 4 h, never with
  accepted work, a load, a drain, an update or a model switch. A new
  registration starts a new coordinator verification session, which clears
  coordinator states that only a reconnect cleared. Public log lines record
  when routing stops, resumes and each re-registration.

* Test the doctor coordinator traffic check for unauthorized and authorized connections

* Keep the disconnect time across failed reconnects; re-register only while idle

Refactor pass on the serving-readiness change.

- noteCoordinatorConnection reset `since` on every `.disconnected` event.
  The client reports one per failed reconnect attempt (up to every 30 s),
  so `Traffic:` read "disconnected 20s ago" through an hour-long outage.
  A disconnect while already down now keeps `since`.
- A re-registration closes admission before it disconnects, which fails an
  accepted Autopilot command and cancels a startup preload. It now waits for
  the idle test the Autopilot inventory re-registration uses (no accepted
  Autopilot command and no Autopilot busy reason, a superset of the earlier
  checks) and still never starts during an update.
- The "authorizes this connection" log line no longer fires when the models
  were withdrawn while the connection was unauthorized; the re-registration
  line says "at least 15 min".
- A local App Attest signing or bundle problem now gets the install-script
  reinstall that doctor's `app signing` check gives; `update` leaves a
  current version in place.
- `shouldReconnect(workInProgress:)` is now `busy:`, and the policy enum is
  internal: only ProviderCore and its tests use it.
- The status traffic test moves to the end of its suite, away from the
  served-count test another branch inserts at the same place.

* Merge follow-up (#1620 interplay): no traffic verdict while an add-on holds the Mac

With master's add-on hold (#1620) merged, a held provider stays connected
and authorized but leaves routing on purpose (status: draining). The
traffic verdict ignored the hold: `darkbloom status` printed
"Not serving: held by add-on ..." followed by "Traffic: eligible for
coordinator work (App Attest authorized until ...)", doctor passed
`coordinator traffic`, and once the lease lapsed or a reconnect under the
hold went unconfirmed both reported "NOT receiving coordinator work" with
an authorization cause and a `darkbloom restart` fix, which a hold
survives.

ServingReadiness.verdict now returns no verdict while an add-on holds a
connected Mac, so status omits the Traffic line (as it does beside a
drain line) and doctor skips the check. A disconnect is still reported.
Re-registration needed no change: superviseServingAuthorization already
waits while autopilotBusyReasons() is non-empty, which includes
addon_hold.

Tests (fail on the merge commit, pass here):
- ServingReadinessTests.aConnectionAnAddonHoldsHasNoVerdict
- StatusCommandRunTests.heldProviderHasNoTrafficVerdict

Docs: cli-reference (Traffic line), troubleshooting (coordinator traffic
row); changelog fragment coordinator-traffic-verdict.md updated in place.

---------

Co-authored-by: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com>
@Gajesh2007 Gajesh2007 mentioned this pull request Oct 27, 2026
7 of 9 tasks
jonathan308 added a commit that referenced this pull request Nov 8, 2026
…r another model blocked them

A selected model left cold by memory (skipped by the startup preload, or
unloaded by an Autopilot operation to place another model) is retried from
the capacity tick until it is resident again, evicting only idle models
outside the selection within Autopilot's victim rules. `darkbloom status`
says why it waits and when a saved `enabled_models` differs from the
running selection. Shutdown waits at most 15 s per unload instead of
forever for a slot whose native retirement never finishes.

Rebased onto dev as one commit (was 17 commits plus four master merges on
master). The merges carried the #1606 drain and #1620 add-on hold
resolutions, so the branch's net change is re-applied instead of replaying
each commit. Resolved against dev: #1730's operator model filter
(`operatorModelFilter`) is kept beside this PR's `savedEnabledModels` and
`enabledModelsAtLastSwitch`; `DaemonState.registeredModels` is kept beside
the new optional keys; the add-on hold calls dev's `publishBusy()`; the
recovery invariant in model-autopilot.md is numbered 11 after dev's
operator-filter invariant 10.
jonathan308 added a commit that referenced this pull request Nov 8, 2026
…r another model blocked them

A selected model left cold by memory (skipped by the startup preload, or
unloaded by an Autopilot operation to place another model) is retried from
the capacity tick until it is resident again, evicting only idle models
outside the selection within Autopilot's victim rules. `darkbloom status`
says why it waits and when a saved `enabled_models` differs from the
running selection. Shutdown waits at most 15 s per unload instead of
forever for a slot whose native retirement never finishes.

Rebased onto dev as one commit (was 17 commits plus four master merges on
master). The merges carried the #1606 drain and #1620 add-on hold
resolutions, so the branch's net change is re-applied instead of replaying
each commit. Resolved against dev: #1730's operator model filter
(`operatorModelFilter`) is kept beside this PR's `savedEnabledModels` and
`enabledModelsAtLastSwitch`; `DaemonState.registeredModels` is kept beside
the new optional keys; the add-on hold calls dev's `publishBusy()`; the
recovery invariant in model-autopilot.md is numbered 11 after dev's
operator-filter invariant 10.

This branch was successfully deployed

5 active deployments
Preview – d-inference — e164315d Deployed Oct 27, 2026 by vercel[bot]
Preview – d-inference-landing — e164315d Deployed Oct 27, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — e164315d Deployed Oct 27, 2026 by vercel[bot]
Preview – eigen-homepages-darkbloom — e164315d Deployed Oct 27, 2026 by vercel[bot]
Preview – darkbloom-status — e164315d Deployed Oct 27, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants